<template>
  <div style="padding: 10px;margin-bottom: 50px">
    <el-row>
      <!--左侧在线用户列表-->
      <el-col :span="4">
        <el-card style="width: 300px;height: 300px;color: #333333">
          <div style="padding-bottom: 10px;border-bottom: 1px solid #cccccc">
            在线用户<span style="font-size: 12px">(点击聊天气泡开始聊天)</span>
          </div>
          <div style="padding: 10px 0;" v-for="user in users" :key="user.username">
            <span>{{ user.username }}</span>
            <i class="el-icon-chat-dot-round"
               style="margin-left: 10px;font-size: 16px;cursor: pointer;"
               @click="chatUser = user.username"></i>
            <span style="font-size: 12px;color: limegreen;margin-left: 5px;" v-if="user.username === chatUser">chatting...</span>
          </div>
        </el-card>
      </el-col>
      <!--右侧发送消息区域-->
      <el-col :span="20">
        <div style="width: 800px;margin: 0 auto;background-color: white;border-radius: 5px;box-shadow: 0 0 10px #cccccc">
          <!--聊天框头部-->
          <div style="text-align: center;line-height: 50px;">
            在线接诊(<span style="color: #3a8ee6">{{ chatUser }}</span>)
          </div>
          <!--消息显示区域-->
          <div style="height: 350px;overflow: auto;border-top: 1px solid #cccccc" v-html="content" id="mainContent"></div>
          <!--发送消息区域-->
          <div style="height: 200px;">
            <textarea v-model="text"
                      style="height: 160px;width: 100%;padding: 20px;border: none;border-top: 1px solid #cccccc;border-bottom: 1px solid #cccccc;outline: none"
                      >
            </textarea>
            <div style="text-align: right;padding-right: 10px">
              <el-button type="primary" size="mini" @click="send">发送</el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>

import {serverIp, serverPort} from "../../../public/config";

let socket;

export default {
  name: "LiveChat",
  data() {
    return {
      users: [],
      user: {},
      chatUser: "",
      text: "",
      content: "",
      messages: []
    }
  },
  methods: {
    send() {
      if (!this.chatUser) {
        this.$message({type: 'warning', message: '请选择聊天对象'})
        return;
      }
      if (!this.text) {
        this.$message({type: 'warning', message: '请输入聊天内容'})
      } else {
        if (typeof (WebSocket) == "undefined") {
          console.log("您的浏览器不支持WebSocket")
          this.$message.error("您的浏览器不支持WebSocket")
        } else {
          console.log("您的浏览器支持WebSocket")
          //组装待发送的消息
          //格式：   {"from":"zhangsan","to":"admin","text":"聊天文本"}
          let message = {from: this.user.username, to: this.chatUser, text: this.text}
          //将组装好的json给服务端，由服务端进行转发
          socket.send(JSON.stringify(message))
          this.messages.push({user: this.user.username, text: this.text})
          //构建页面显示的本人消息
          this.createContent(null, this.user.username, this.text)
          this.text = ""
          //让滚动条滚动到最下面
          var divContent = document.getElementById("mainContent")
          divContent.scrollTop = divContent.scrollHeight
        }
      }
    },
    //用来将json的聊天消息数据转换成html
    createContent(remoteUser, nowUser, text) {
      let html;
      //当前用户消息
      if (nowUser) {
        html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
            "  <div class=\"el-col el-col-22\" style=\"text-align: right; padding-right: 10px\">\n" +
            "    <div class=\"tip left\">" + text + "</div>\n" +
            "  </div>\n" +
            "  <div class=\"el-col el-col-2\">\n" +
            "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
            "    <img src=\"https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png\" style=\"object-fit: cover;\">\n" +
            "  </span>\n" +
            "  </div>\n" +
            "</div>";
      } else if (remoteUser) {
        //远程用户消息
        html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
            "  <div class=\"el-col el-col-2\" style=\"text-align: right\">\n" +
            "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
            "    <img src=\"https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png\" style=\"object-fit: cover;\">\n" +
            "  </span>\n" +
            "  </div>\n" +
            "  <div class=\"el-col el-col-22\" style=\"text-align: left; padding-left: 10px\">\n" +
            "    <div class=\"tip right\">" + text + "</div>\n" +
            "  </div>\n" +
            "</div>";
      }
      // console.log("消息内容：" + html)
      this.content += html
    },
    init() {
      this.user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
      let username = this.user.username
      let _this = this
      if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket")
        this.$message.error("您的浏览器不支持WebSocket")
      } else {
        console.log("您的浏览器支持WebSocket")
        let socketUrl = `ws://${serverIp}:${serverPort}/imserver/` + username;
        if (socket != null) {
          socket.close()
          socket = null
        }
        //开启一个websocket服务
        socket = new WebSocket(socketUrl)
        //打开事件
        socket.onopen = function () {
          console.log("websocket已经打开")
        }
        //获得消息事件
        //浏览器接收消息，获得从服务器端发送过来的文本消息
        socket.onmessage = function (msg) {
          console.log("收到数据===" + msg.data)
          //对收到的json消息进行解析
          let data = JSON.parse(msg.data)
          if (data.users) {
            //获取在线人员信息
            //获取当前连接的所有用户信息，并且排除自身
            _this.users = data.users.filter(user => user.username !== username)
          } else {
            //如果服务端发送过来的json数据不包含users这个key，那么发送过来的就是聊天文本json数据
            //格式：{"from":"zhangsan","text":"hello"}
            if (data.from === _this.chatUser) {
              _this.messages.push(data)
              //构建消息内容
              _this.createContent(data.from, null, data.text)
            }
          }
        };
        //关闭事件
        socket.onclose = function () {
          console.log("websocket已经关闭")
        };
        //发送错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误")
        };
      }
    },
    watchEnter(e) {
      if (e.keyCode === 13 && e.shiftKey) {
        this.text += '\n'
        return
      }
      // console.log("===" + e.shiftKey)
      let key = window.event ? e.keyCode : e.which
      if (key === 13) {
        if (this.text.length !== 1) {
          console.log(this.text.length)
          this.send()
          this.text = ""
        }else {
          this.$message({type: 'warning',message: "请先输入要发送的消息"})
          this.text = ""
        }
      }
    }
  },
  created() {
    this.init()
  },
  mounted() {
    document.addEventListener("keyup",this.watchEnter)
  }
}
</script>

<style>
.tip {
  color: white;
  text-align: center;
  border-radius: 10px;
  font-family: sans-serif;
  padding: 10px;
  width:auto;
  display:inline-block !important;
  display:inline;
}

.right {
  background-color: deepskyblue;
}
.left {
  background-color: forestgreen;
}
</style>